package org.sraosha.springboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.sraosha.springboot.enumeration.ApiResultEnum;
import org.sraosha.springboot.pojo.ApiResult;
import org.sraosha.springboot.pojo.ServiceResult;
import org.sraosha.springboot.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录的controller类
 */
@Api(value = "登录的controller类", tags = "LoginController")
@RestController
@RequestMapping("api/v1/login")
@Slf4j
public class LoginController extends AbstractController {

    /**
     * 根据前端给定微信登录的code获取openid
     * @param code
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("根据前端给定微信登录的code获取openid")
    @ApiImplicitParam(name = "code", value = "微信登录的code", required = true, dataType = "String")
    @RequestMapping(value = "/wechat/jscode2session/{code}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<String>> jscode2session(@PathVariable String code, HttpServletRequest request, HttpServletResponse response) {
        ApiResult apiResult = new ApiResult();
        if (StringUtils.isEmpty(code)) {
            String message = "调用接口【/api/v1/login/wechat/jscode2session/{code}时，" + ApiResultEnum.PARAMETER_EMPTY;
            log.warn(message);
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<String> serviceResult = loginService.jscode2session(code);

        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(serviceResult.getMessage());
        apiResult.setResult(serviceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}
